var System = {
    /*CRIACAO DE CAMADAS DINAMICAS*/
    createdata  : {
        create  : function(to, id){$(to).append("<div id='"+id+"'></div>");},
        message : function(to, classe, msg, response){
		  	$(to).append("<div class='"+classe+"' style='display:none;'>" +
			  			"<div>"+
			  			  "<div style='float:left'><h3>"+msg+"</h3></div>"+
			  			  "<div style='float:right; text-align: right;'>"+
			  			    "<div class='close'>"+
			  			      "<a href='#fechar' class='icoFechar' id='closeTopMessage'></a>"+
			  			    "</div>" +
			  			  "</div>" +
			  			"</div>"+
			  			"<div style='clear:both'>"+response+"</div>"+
			  		    "<ol></ol>" +
		  		    "</div>");
		  	$('#closeTopMessage').click(function(){$('div.'+ classe).hide();});
		},
        modal   : function(to, params){$(to).append("<div id='conteudo-ajax'></div>");}
    },
    /*TRATAMENTO DE TAGS OU INPUTS DO CORPO*/
    bodydata : {
    	loading:    function()
        {
    		$('body').append('<div id="top_loading"></div>');
    		$("#top_loading").hide().html('Aguarde ...');
    		$().ajaxStart(function(){$("#top_loading").show();});
    		$().ajaxStop(function(){$("#top_loading").hide();});
        },
        disable:    function(id){$(id).attr("disabled", "disabled");},
        even:       function(id,cor){$(id+":even").css("background-color", cor);},//deve ser passado o id como "#minhaul > li", ou se for tabela "table > tr"
        accordion:  function(id){},//requer plugin accordion, dimensions e easing
        calendar:   function(id, params){$(id).datepicker(params);},//requer plugin datepicker - já incluso na jqueryUI
        toTab:      function(id, options)
        {
                $(id).tabs(options);
        },
        slide:     function(idOpen, idClose, toOpen)
        {
            $(idOpen).click(function(){$(toOpen).slideDown();return false;});
            $(idClose).click(function(){$(toOpen).slideUp();});
        },
        loader:     function(id, toload){$(id).load(toload);},
        toClone:    function(id, toappend)
        {
            $(id).click(function()
            {
                $(toappend).append('<li><div style="float:left;"><label>Imagem:</label><br /><input type="file" name="itemFile[]"  /></div></li><br />');
            });
        },
        toSrc: function(to)
        {
            $("a[id^='src']").hover(function()
            {
               $(to).attr("src", $(this).attr("href"));
               return false;
            });
        },
        //Aplicando ToolTip
        toTip: function(id, uri, position)
        {
           
            $("a[id="+id+"]").each(function(){
               var aux  =    this;
               $(aux).qtip({
               content: {url: uri, data: {idt: $(aux).attr("rel")}, method: 'post'},
                   style: {
                       border: {
                         width: 2,
                         radius: 1,
                         color: '#305258'
                      },
                      width:150,
                      tip: 'leftMiddle',
                      name: 'light' // Inherit the rest of the attributes from the preset dark style
                   },
                   position: {
                       adjust: position
                    }
                });
            });
        }
    },
    /*TRATAMENTOS DE ERROS AO SISTEMA*/
    messagedata : {
        clear: function ()
        {
        	$("div[class^='msg']").each(function(){ $(this).remove(); });
        },
        slideMessage: function(message, go, time)
        {
            if(message == undefined){$("div.top-message").slideUp();}
            else
            {
                $("div.top-message").html(message);
                $("div.top-message").slideDown();
                if(go)  {setTimeout(function(){location.href = go;}, time);}
                else    {setTimeout(function(){$("div.top-message").slideUp();}, time);}

            }
            return false;
        },
        alert:  function(type, response, label)
        {
        	System.messagedata.clear();
        	System.createdata.message("#mensagens", 'msg'+type, label, response);
        	$('div.msg'+type).show();
        },
        success: function(response, status, xhr, form) 
        {	
        	System.messagedata.alert('Sucesso', response.result, 'Sucesso');
        },
        message: function(response, status, xhr, form)
        {
        	if(response.success)
        		System.messagedata.alert('Sucesso', response.success, 'Sucesso');
        	else
        		System.messagedata.alert('Erro', response.erro, 'Erro');
        	
        	if($("#conteudo-ajax").dialog( 'isOpen' ))
        		$("#conteudo-ajax").dialog("destroy");
        		
        }
        
    },
    /*JANELAS MODAIS AO SISTEMA - requer até então, o plugin simple-modal*/
    modaldata : {
        onClick: function(id, inner, type, params)
        {
            $("a[id='"+id+"']").click(function()
            {
            	$("#conteudo-ajax").dialog("destroy");
                $("#conteudo-ajax").html('');
                $("#conteudo-ajax").load($(this).attr("href"));
                if(type)
                {
                    if(type == "dialog")
                    {
                    	System.modaldata.openDialog("#conteudo-ajax", params);
                    	return false;
                    }
                    else if(type == "modal") {$.modal($("#"+inner));return false;}
                    else if(type == "lightbox"){alert('lighbox');return false;}
                }
            });
        },
        openDialog: function(id, params)
        {
            if($(id).dialog( 'isOpen' ) == false)
                $(id).dialog('open');
            else 
            {
            	$("#conteudo-ajax").dialog( "destroy" );
            	$(id).dialog(params);
            }
            
            
        }
    },
    /*TRATAMENTO DE FORMULARIOS - requer plugins validate, form, metadata*/
    formdata : {
    	save: function (ajax, tipo, callback)
        {
    		var callbackFunction = System.messagedata.success;
    		if(callback) callbackFunction = callback;
    		
    		if(!tipo) var tipo = 'html';
    		
            var continua = true;
            
            var validator = $("form").each(function()
            {
                $(this).validate({
                    submitHandler: function(form)
                    { 
                		var options ={
                            url: $(form).attr("action"),
                            type: 'post',
                            dataType: tipo,
                            target: "#result",
                            success: eval(callbackFunction)
                        };
                           
                        if(ajax)
                        {
                        	$(form).ajaxSubmit(options);
                        	return false;
                        }
                        else
                        	$(form).submit();
                        
                        return false;
                   }
                });
            });
        },
        remove: function(ajax, reload)
        {
            $("a[id=delete]").click(function(){
            if(confirm("Tem certeza que deseja excluir esse registro?"))
            {
                    var action = $(this).attr("href");

                    $.post(action, {
                    }, function(response) {
                        //alert(response);
                        if(reload)
                            location.href = reload;
                        
                        if($("#reload").val() != undefined)
                                $("#"+$("#parent_div").val()).load($("#reload").val());
                    });

                    return false;
             }
             else
                    return false;
            });
           
        },
        uploader: function(id, img, inpt, show)//uploader de imagem temporario- requer plugin uploadify
        {           
            $(id).uploadify({
                    'uploader'  : 'http://static.redefenam.provisorio.ws/js/uploadify.swf',
                    //'uploader'  : 'http://localhost:69/js/uploadify.swf',
                    'script'    : 'midia/upload/upload.php',
                    'auto'      : true,
                    'folder'    : '/midia/upload/tmp/',
                    'buttonText': 'Incluir foto',
                    'scriptAccess':  'always',
                    'fileExt'   :   '*.jpg;*.gif;*.jpeg',
                    'fileDesc'  :   '*.jpg;*.gif;*.jpeg',
                    onSelect    : function(event, queueID, fileObj, response, data)
                    {
                        
                    },
                    onComplete	: function(event, queueID, fileObj, response, data)
                    {
                            
                            //var pathlocal='http://localhost:69/';
                            var pathlocal='http://static.redefenam.provisorio.ws/';
                            
                    }
            });
        },
        multiuploader: function(id, toshow, btn, post)//upload-multiplo
        {
            $(id).uploadify({
                    'uploader'  : 'http://static.redefenam.provisorio.ws/js/uploadify.swf',
                    //'uploader'  : 'http://localhost:69/js/uploadify.swf',
                    'script'    : 'midia/upload/upload-direct.php?postid='+post,
                    'folder'    : '/midia/upload/',
                    'buttonText': 'Incluir mídia',
                    'scriptAccess':  'always',
                    'multi'     : true,
                    'auto'      : true,
                    'fileExt'   :   '*.jpg;*.gif;*.jpeg',
                    'fileDesc'  :   '*.jpg;*.gif;*.jpeg',
                    onSelect    : function(event, queueID, fileObj, response, data)
                    {
                        $(btn).show();
                    },
                    onAllComplete	: function(event, queueID, fileObj, response, data)
                    {
                        $(toshow).load("/ajax/foto-album/"+post);
                        $(btn).hide();
                    }
            });
        },
        cropImage: function()
        {
            //Criar método de crop
        },
        editInPlace: function(action)//requer o plugin jeditable
        {
            $("div[edit='true']").editable(action, {
            onblur    : "submit",
            indicator : "Aguarde...",
            tooltip   : "Clique para editar...",
            name:     $(this).attr("myname"),
            style  : "inherit"
            });
        },
        btn : function(params, responseType, callback)
        {
            $("input[name^='btn']").click(function()
            {
                System.loaddata.innerPage($(this).attr("action"), $(this).attr("rel"), params, responseType, callback);
            });
        },
        mask : function(){
            $("input[typedata='timestamp']").mask("99/99/9999");
            $("input[typedata='time']").mask("99:99");
            $("input[typemask='intCEP']").mask('99999-999');
            $("input[typemask='intCPF']").mask('999.999.999-99');
        },
        search: function (ajax)
        {
            System.createdata.message("body");
            var container = $('div.top-message');
            var validator = $("form[name^='search']").each(function()
            {
                $(this).validate({
                    errorContainer: container,
                    errorLabelContainer: $("ol", container),
                    wrapper: 'li',
                    meta: "validate",
                    submitHandler: function(form)
                    {

                       var options =
                         {
                             url: $(form).attr("action"),
                             type: 'post',
                             success:
                             function(response)
                             {
                                 $("#friends").html(response);
                             }
                         };
                         $(form).ajaxSubmit(options);
                         return false;
                   }
                });
            });
        }
    },
    /*CARREGAR PAGINAS POR AJAX*/
    loaddata : {
        innerPage: function(action, to, params, responseType, callback)
        {
            $.post(action, params , function(response)
            {
                $(to).html(response);
                return false;
            });
        },
        innerText: function(to, text){$(to).html(text);},
        onChange: function(id, value)//Carrega um conteudo no evento change.
        {
            $(id).change(function()
            {
                if(value){var data = $(this).attr("value");} else{var data = $(this).attr("page");}
                this.inner($(this).attr("action"), data, $(this).attr("inner"));
            });
        },
        onClick: function(id, to, params)
        {
            $("a[id='"+id+"']").click(function(){
                System.loaddata.innerPage($(this).attr("href"), to, params);
                return false;
            });
        },
	    showdata : {
	        onChange: function(id, div)
	        {
	            $(id).change(function()
	            {
	                if($(this).val() == "true") {$(div).show();}
	                else{$(div).hide();}
	            });
	        },
	        onHover:  function(id, div, sub)
	        {
	            $(id).hover(function() {$(div).show();});
	            $(div).hover(function(){}, function(){$(this).hide();});
	        },
	        onClic: function(id, div, toclear)
	        {
	            $("input[id='"+id+"']").click(function()
	            {
	                if($(this).val() == 'true')
	                    $(div).show();
	                else
	                {
	                    $(toclear).val('');
	                    $(div).hide();
	                }
	                    
	            });
	        },
	        onClic2: function(id, div, toclear)
	        {
	            $("input[id='"+id+"']").click(function()
	            {
	                if($('#'+id).attr('checked'))
	                    $(div).show();
	                else
	                {
	                    $(div).hide();
	                }
	
	            });
	        }
	    },
	    preloaddata : {
	        setajax : function(to, text)
	        {
	            $().ajaxStart(function(){System.loaddata.innerText(to, text);});
	            $().ajaxStop(function(){System.loaddata.innerText(to, '');});
	        }
	    }
    }
};

$(document).ready(function(){
	$('#closeTopMessage').click(function(){ $('#mensagens').hide();});
});